<template>
   <header class="w-full shadow-md">
    <div class="container mx-auto">
      <div class="flex items-center justify-between py-4">
        <!-- Logo部分 -->
        <div class="flex items-center">
          <img src="@/assets/img/Tencent_EN.png" alt="Logo" class="h-8">
        </div>
        
        <!-- 搜索框部分 -->
        <div class="flex items-center relative" ref="searchContainer">
          <input 
            type="text" 
            placeholder="Input Part Number / Keyword" 
            v-model="searchText"
            style="width: 500px"
            class="px-4 py-2 border border-gray-300 rounded-l-md focus:outline-none focus:border-primary"
            @input="handleInput"
          >
          <div  v-if="suggestions.length" class="absolute bg-white border rounded shadow-lg mt-1 w-full z-11" style="top: 40px; z-index: 100 ;">
            <ul>
              <li
                v-for="suggestion in suggestions"
                :key="suggestion.PID"
                @click="selectSuggestion(suggestion)"
                class="p-2 cursor-pointer hover:bg-gray-200"
              >
                {{ suggestion.MFG }} -- 
                {{ suggestion.MFGPartNo }}
              </li>
            </ul>
          </div>
          <button 
            @click="handleSearch"
            class="px-4 py-2 bg-primary text-white rounded-r-md hover:bg-opacity-90"
          >
            Search
          </button>
        </div>
        
        <!-- 登录部分 -->
        <div class="flex items-center space-x-4" >
          info@indctl.com
        </div>
      </div>
    </div>
    
    <!-- 导航菜单 -->
    <nav class=" w-full shadow-md relative z-10 nav-menu">
      <div class="container mx-auto">
        <div class="flex space-x-8 py-4">
          <router-link 
            v-for="item in menuItems" 
            :key="item.path" 
            :to="item.path"
            class="text-gray-600 hover:text-primary text-center transition-colors"
            :class="{ 'text-primary font-medium': $route.path === item.path }"
          >
            {{ item.name }}
          </router-link>
        </div>
      </div>
    </nav>
  </header>
</template>

<script lang="ts" setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { useRouter } from 'vue-router'
import { debounce } from 'lodash-es'
import { useNuxtApp } from '#app'
import { useProductStore } from '~/store/productStore'
const product = useProductStore()
const { $request } = useNuxtApp() // 获取 Axios 实例
const router = useRouter() // 获取路由实例
const searchText = ref('')
const suggestions = ref([]) // 存储建议列表
const menuItems = ref([
  { name: 'Home', path: '/home' },
  { name: 'Brand', path: '/brand' },
  { name: 'Product', path: '/product' },
  { name: 'Send RFQ', path: '/rfq' },
  { name: 'About', path: '/about' },
])

const searchContainer = ref(null)

const handleClickOutside = (event) => {
  if (searchContainer.value && !searchContainer.value.contains(event.target)) {
    suggestions.value = []
  }
}

// 防抖函数
const fetchSuggestions = debounce(async () => {
  if (searchText.value) {
    try {
      const response = await $request.post(`https://api.indtrd.com/api/v1/partno/associateasync`, 
        {
          PrePartNo: searchText.value,
          Limit: 5
        }
      )
      suggestions.value = response.Data.PartNoListModels // 假设返回的数据是建议列表
    } catch (error) {
      console.error('Error fetching suggestions:', error)
    }
  } else {
    suggestions.value = [] // 清空建议
  }
}, 300) // 300ms 防抖

// 输入事件处理
const handleInput = () => {
  fetchSuggestions() // 调用防抖函数
}

// 选择联想内容
const selectSuggestion = (suggestion) => {
  searchText.value = suggestion.StandPartNo
  handleSearch()
  // 关闭联想框
  suggestions.value = []
}

// 搜索事件处理
const handleSearch = () => {
  if (!searchText.value) {
    return
  }
  router.push({ path: '/product', query: { search: searchText.value } })
  product.setKeyword(searchText.value)
  product.fetchProducts()
}



const handleLogin = () => {
  console.log('登录')
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onBeforeUnmount(() => {
  document.removeEventListener('click', handleClickOutside)
})

</script>

<style scoped lang="scss">
.header {
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1rem 2rem;
}

.nav-menu {
  border-top: 1px solid #f0f0f0;
}

.nav-menu a {
  text-decoration: none;
  color: #333;
}

.nav-menu a:hover {
  color: #1890ff;
}

.nav-menu a.router-link-active {
  color: #1890ff;
}

.logo {
  width: 200px;
  img {
    width: 100%;
    object-fit: cover;
  }
}
</style>